package com.agrm.stmq.service.impl;

import com.agrm.api.client.GoodClient;
import com.agrm.api.client.OrderClient;
import com.agrm.model.common.dtos.ResponseResult;
import com.agrm.model.order.pojo.Order;
import com.agrm.model.order.pojo.OrderItem;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@RocketMQMessageListener(topic = "shoplook2025-orderseckill-check", consumerGroup = "g2")
@Service
public class OrderCheckServiceImpl implements RocketMQListener<String> {
    private RedisTemplate<String, Object> redisTemplate;
    private OrderClient orderClient;
    private GoodClient goodClient;

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    //监听到消息队列的消息，即秒杀订单
    @Override
    public void onMessage(String no) {

        //创建订单，扣除库存
        ResponseResult<Order> save = orderClient.getOrderByNo(no);
        Order order = save.getData();
        if (order != null) {
            if (order.getStatus().equals(0)) {
                Order forUpdate = new Order();
                forUpdate.setId(order.getId());
                forUpdate.setStatus(4);
                ResponseResult<Boolean> isSuccessful = this.orderClient.update(forUpdate);
                Boolean successfulData = isSuccessful.getData();
                if (successfulData != null && successfulData) {
                    List<OrderItem> items = this.orderClient.findByItemId(order.getId()).getData();
                    if (items != null && !items.isEmpty()) {
                        Integer goodId = items.get(0).getGoodId();
                        this.redisTemplate.opsForValue().increment("seckill-stock:" + goodId);
                        this.goodClient.updateQty(goodId,1);
                    }
                }

            }
        }
    }

    @Autowired
    public void setOrderClient(OrderClient orderClient) {
        this.orderClient = orderClient;
    }

    @Autowired
    public void setGoodClient(GoodClient goodClient) {
        this.goodClient = goodClient;
    }
}
